/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ep.m005.ui.controllers;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import com.vaadin.data.util.BeanItem;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.terminal.gwt.server.WebApplicationContext;
import ep.libs.implementations.AbstractModule;
import ep.m002.bl.BL002Controller;
import ep.persistence.entities.SavePrescriptionBean;
import ep.persistence.entities.T002Doctor;
import ep.persistence.entities.T005Patient;
import ep.persistence.entities.T005T007;
import ep.persistence.entities.T006Prescription;
import ep.persistence.entities.T008Dosage;
import ep.persistence.entities.T009Medicine;
import ep.persistence.entities.T010Substance;
import ep.persistence.entities.T012Diagnosis;
import ep.persistence.entities.T013Frequency;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

/**
 *
 * @author Spyros
 */
public class M005Controller {

    private AbstractModule module;
    private T006Prescription prescription;
    private T005Patient patient;
    private T002Doctor doctor;
    private WebResource service;

    public M005Controller(Object patientObject, Integer prescriptionId, AbstractModule module) {
        this.patient = (T005Patient) patientObject;
        this.module = module;
        ClientConfig config = new DefaultClientConfig();
        Client client = Client.create(config);
        config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
        service = client.resource(UriBuilder.fromUri("http://localhost:8080/EPrescribing/rest").build());
        findPrescription(prescriptionId);
        findDoctor();
    }

    public BeanItem<T005Patient> getPatientDataSource() {
        BeanItem<T005Patient> beanItem = new BeanItem<T005Patient>(patient);
        return beanItem;
    }

    public BeanItem<T002Doctor> getDoctorDataSource() {
        BeanItem<T002Doctor> beanItem = new BeanItem<T002Doctor>(doctor);
        return beanItem;
    }

    public BeanItem<T006Prescription> getPrescDataSource() {
        BeanItem<T006Prescription> beanItem;
        if (prescription == null) {
            prescription = new T006Prescription();
        }
        beanItem = new BeanItem<T006Prescription>(prescription);
        return beanItem;
    }

    public BeanItemContainer<T008Dosage> getDosageDataSource() {
        BeanItemContainer<T008Dosage> beanItemContainer;
        if (prescription == null) {
            beanItemContainer = new BeanItemContainer<T008Dosage>(T008Dosage.class);
        } else {
            beanItemContainer = new BeanItemContainer<T008Dosage>(T008Dosage.class, prescription.getT008DosageCollection());
        }
        return beanItemContainer;
    }

    public BeanItemContainer<T012Diagnosis> getDiagnosisDataSource() {
        Collection collection = service.path("bl005").path("diagnosis").
                get(new GenericType<Collection<T012Diagnosis>>() {
        });
        return new BeanItemContainer<T012Diagnosis>(T012Diagnosis.class, collection);
    }

    public BeanItemContainer<T013Frequency> getFrequencyDataSource() {
        Collection<T013Frequency> tfs = service.path("bl005").path("frequency").
                get(new GenericType<Collection<T013Frequency>>() {
        });
        BeanItemContainer<T013Frequency> beanItemContainer = new BeanItemContainer<T013Frequency>(T013Frequency.class, tfs);
        return beanItemContainer;
    }

    public BeanItemContainer<T009Medicine> getMedicineDataSource() {
        Collection<T009Medicine> tms = service.path("bl005").path("medicine").
                get(new GenericType<Collection<T009Medicine>>() {
        });
        BeanItemContainer<T009Medicine> beanItemContainer = new BeanItemContainer<T009Medicine>(T009Medicine.class, tms);
        return beanItemContainer;
    }

    public String checkSubstances(Collection dosages) {
        final Collection<T010Substance> patientSubstances = new ArrayList<T010Substance>();
        for (Iterator<T005T007> it = patient.getT005T007Collection().iterator(); it.hasNext();) {
            T005T007 t005t007 = it.next();
            patientSubstances.addAll(t005t007.getT007Illness().getT010Substances());
        }
        for (Iterator it = dosages.iterator(); it.hasNext();) {
            T008Dosage t008Dosage = (T008Dosage) it.next();
            Collection medicSubs = t008Dosage.getT009Medicine().getT010Substances();
            for (Iterator it1 = medicSubs.iterator(); it1.hasNext();) {
                T010Substance substance = (T010Substance) it1.next();
                if (patientSubstances.contains(substance)) {
                    return substance.getName();
                }
            }
        }
        return null;
    }

    public boolean save(BeanItem prescBeanItem, Collection dosages) {
        return save(prescBeanItem, dosages, false);
    }

    public boolean save(BeanItem prescBeanItem, Collection dosages, boolean repeat) {
        T006Prescription localPrescription = (T006Prescription) prescBeanItem.getBean();
        SavePrescriptionBean bean = new SavePrescriptionBean(doctor, patient, localPrescription, dosages, repeat);
        ClientResponse clientResponse = service.path("bl005").path("spresc").
                accept(MediaType.TEXT_PLAIN).post(
                ClientResponse.class, new GenericEntity<SavePrescriptionBean>(bean, SavePrescriptionBean.class));
        String response = clientResponse.getEntity(String.class);
        return response.equals("0");
    }

    private void findDoctor() {
        BL002Controller bL002Controller = new BL002Controller();
        String username = (String) ((WebApplicationContext) module.getApplication().getContext()).getHttpSession().getAttribute("username");
        if (prescription != null && prescription.getT002Doctor() != null) {
            doctor = prescription.getT002Doctor();
        } else {
            doctor = bL002Controller.findDoctor(username);
        }
    }

    private void findPrescription(Integer id) {
        if (id > 0) {
            T006Prescription presc = service.path("bl005").path("prescription").queryParam("id", id.toString()).
                    accept(MediaType.APPLICATION_JSON).get(T006Prescription.class);
            prescription = presc;
        }else{
            prescription = null;
        }

    }
}
